function clearAddressFormError()
{
	$("#firstname_error").html("");
	$("#address_error").html("");
	$("#postcode_error").html("");
	$("#street_error").html("");
	$("#phone_error").html("");
	$("#telephone_error").html("");
	$(".error").removeClass("error");
}

function checkAddressForm(){
	clearAddressFormError();
	//alert("clear error");
	var flag = true;
	var firstnameJQ = jQuery("#firstname");
	//alert(firstnameJQ.val());
	if (isEmpty(firstnameJQ.val())){
		$("#firstname_error").html("收货人姓名不能为空");
		firstnameJQ.addClass("error");
		flag = false;
	}else if (firstnameJQ.val().length>20){
		$("#firstname_error").html("收货人姓名不能太长");
		firstnameJQ.addClass("error");
		flag = false;
	}
	//alert("111");
	var regionJQ = $("#region_id");
	var cityJQ = $("#city_id");
	var districtJQ = $("#district_id");

	if (regionJQ.val() == 0){
		$("#address_error").html("请选择省/直辖市");
		regionJQ.addClass("error");
		flag = false;
	}else if (cityJQ.val() == 0){
		$("#address_error").html("请选择城市");
		cityJQ.addClass("error");
		flag = false;
	}else if (districtJQ.val() == 0){
		$("#address_error").html("请选择区县");
		districtJQ.addClass("error");
		flag = false;
	}
	//alert("222");
	//var postcode = jQuery("#postcode").val();
	//var regionName = regionJQ.find("option:selected").text(); ;
	//var indexTW = regionName.indexOf("台湾");
	//var indexAM = regionName.indexOf("澳门");
	//var indexXG = regionName.indexOf("香港");
	//if(indexTW<0 && indexAM<0 && indexXG<0)
	//{
	//	if (isEmpty(postcode) || postcode == "6位数字"){
	//		$("#postcode_error").html("邮编不能为空");
	//		$("#postcode").addClass("error");
	//		flag = false;
	//	}else if (!isPostcode(postcode)){
	//		$("#postcode_error").html("邮编格式不正确");
	//		$("#postcode").addClass("error");
	//		flag = false;
	//	}
	//}

	var streetJQ = $("#street");
	if (isEmpty(streetJQ.val())){
		$("#street_error").html("街道地址不能为空");
		streetJQ.addClass("error");
		flag = false;
	}

	var telephone_area_code = $("#telephone_area_code").val();
    var telephone_number = $("#telephone_number").val();
    var telephone_ext = $("#telephone_ext").val();
    var telphone = telephone_area_code+telephone_number+telephone_ext;

    var telphoneFormat = telephone_area_code+"-"+telephone_number
    if(!isEmpty(telephone_ext) && telephone_ext != "分机号"){
    	telphoneFormat += "-"+telephone_ext;
    }

    var mobileJQ = $("#mobile");
    if (isEmpty(mobileJQ.val()) && isEmpty(telphone)){
    	$("#phone_error").html("手机号码和固定电话请至少填写一项");
    	mobileJQ.addClass("error");
		flag = false;
	}

    if (!isEmpty(telphone) && telphone!="区号电话号码分机号"  && !isPhone(telphoneFormat)){
    	$("#telephone_error").html("固定电话格式错误");
    	$("#telephone_area_code").addClass("error");
    	$("#telephone_number").addClass("error");
    	$("#telephone_ext").addClass("error");
		flag = false;
	}
    if (!isEmpty(mobileJQ.val()) && mobileJQ.val()!="手机号码" && !isMobile(mobileJQ.val())){
    	$("#phone_error").html("手机号码错误");
    	mobileJQ.addClass("error");
		flag = false;
	}
	return flag;
}

function showNewAddressForm()
{
	if(jQuery("#billing_address_id_new")[0].checked)
	{
		clearAddressFormError();
		cleanAddressTable();
		$("#shippingContent").html('');
		$("#addressUl").find("li").removeClass("checked");
		jQuery("#billing_address_id_new").parent().addClass("checked");
		jQuery("#newAddressDiv").show();
	}
	else
	{
		jQuery("#billing_address_id_new").parent().removeClass("checked");
		jQuery("#newAddressDiv").hide();
	}
}

function modifyAddress(addId){
	jQuery("#newAddressDiv").show();

	jQuery.ajax({
		type:'post',
		url: getAddressByIdAjaxUrl+"?id="+addId,
		dataType:"json",
		cache: false,
		async: false,
		beforeSend:function(){},
		complete:function(){},
		error:function(value){
			//alert("获取数据错误");
			var info = "获取数据错误";
			wep.dialog({
				   title : '消息',
				   content : info,
				   onyes : function(){
						this.close();
				   },
				   width : 200,
				   lock : true,
				   icoBasePath : icoBasePath,
				   icon : "error.gif"
			});
		},
		success: function(value){
			var success = value.success;
			var info = value.info;
			if(success==1){
				writeAddress(info);
			}else{
				//alert(info);
				wep.dialog({
					   title : '消息',
					   content : info,
					   onyes : function(){
							this.close();
					   },
					   width : 200,
					   lock : true,
					   icoBasePath : icoBasePath,
					   icon : "error.gif"
				});
			}
		}
	});
}

function writeAddress(jsonData){
	//clearAddressFormError();
	//改变字样
	//$("#addresstitle").html("修改收货地址");
	//$("#default").hide();
	$("#firstname").val(jsonData.firstname);
	$("#addressId").val(jsonData.id);
	$("#region").val(jsonData.region_id);
	changeProvice(jsonData.city_id);
	changeCity(jsonData.district_id,jsonData.city_id);
	//$("#district").val(jsonData.district_id);
	$("#street").val(jsonData.street);
	$("#postcode").val(jsonData.postcode).css({color: "#333"});
	var tel = jsonData.telephone;
	if(tel && tel != "")
	{
		var arrtel = tel.split("-");
		$("#telephone_area_code").val(arrtel[0]).css({color: "#333"});
		$("#telephone_number").val(arrtel[1]).css({color: "#333"});
		$("#telephone_ext").val(arrtel[2]).css({color: "#333"});
	}
	$("#mobile").val(jsonData.mobile).css({color: "#333"});
	jQuery("#newAddressDiv").focus();
	$("#firstname").focus();
	//if(jsonData.default_billing == 1){
	//	$("#default_billing").attr("checked",true);
	//}else{
	//	$("#default_billing").attr("checked",false);
	//}
}
function changeProvice(city_id){
	var
	$ = jQuery,
	city = $('#city')[0],
	province = $('#region')[0],
	district = $('#district')[0],
	postcode = $('#postcode').val('');
	//clear
	city.options.length = 0;
	city.options[0] = new Option('--请选择--', '');
	district.options.length = 0;
	district.options[0] = new Option('--请选择--', '');

	//filter
	var
	postCodeEm = postcode.next().show(),
	noPostCodeCity = ['台湾', '澳门', '香港'],
	currProvince = province.options[province.selectedIndex].text;
	for(var i=0, len=noPostCodeCity.length; i<len; i++){
		if(currProvince.indexOf(noPostCodeCity[i]) > -1){
			postCodeEm.hide();
			break;
		}
	}

	//Insert
	var loading = $('#loading_state').show();
	loading.show();
	$.get(getCityUrl + '?regionId=' + province.options[province.selectedIndex].value, function(data){
		loading.hide();
		var currInx = 0;
		for(var i=0, len=data.length; i<len; i++){
			if(city_id == data[i].id){
				currInx = i + 1;
			}
			city.options[i + 1] = new Option(data[i].city_name, data[i].id);
		}
		city.selectedIndex = currInx;
	}, 'json');
}

function changeCity(district_id,city_id)
{
	var city = jQuery("#city");
	getPostCode(city);
	var district = jQuery("#district")[0];
	district.options.length = 0;
	district.options[0] = new Option('--请选择--', '');
	district.options[1] = new Option('其他', 0);

	var loading = $('#loading_state').show();
	loading.show();
	$.get(getDistrictUrl+"?cityId=" + ((city_id)?city_id:city.val()), function(value){
		loading.hide();
		var currInx = 0;
		for (var i = 0; i < value.length; i++)
		{
			var id = value[i].id;
			var disName = value[i].dis_name;
			var selected = false;
			if(district_id && district_id==id ){
				currInx = i + 2;
			}
			district.options[i + 2] = new Option(disName, id);
		}
		if(district_id == 0)
		{
			district.selectedIndex = 1;
		}
		else
		{
			district.selectedIndex = currInx;
		}
	}, 'json');
}

function getPostCode(city)
{
	var city_id = city.val();
	if(city_id)
	{
		jQuery.ajax({
			type:'get',
			url: getPostCodeUrl+"?cityId=" + city_id,
			dataType:"json",
			cache: false,
			async: true,
			beforeSend:function()
			{
				jQuery("#loading_state").show();
			},
			complete:function()
			{
				jQuery("#loading_state").hide();
			},
			success: function(value)
			{
				if(value != "")
				{
					jQuery("#postcode").val(value.post_code);
				}
			}
		});
	}
	else
	{
		jQuery("#postcode").val('');
	}
}

function cleanAddressTable()
{
	$("#addressId").val('');
	$("#firstname").val('');
	$("#region_id").val('');
	$("#city_id").val('');
	$("#district_id").val('');
	$("#postcode").val('');
	$("#street").val('');
	$("#mobile").val('');
	$("#telephone_area_code").val('');
	$("#telephone_number").val('');
	$("#telephone_ext").val('');
}

function saveAddressDefault(id)
{
	jQuery.ajax({
		type:'post',
		url: getAddressSetDefaultAjaxUrl,
		data:{"addressId":id},
		dataType:"json",
		cache: false,
		async: true,
		error:function(value)
		{
			var info = "设置默认失败";
			wep.dialog({
				   title : '消息',
				   content : info,
				   onyes : function(){
						this.close();
				   },
				   width : 200,
				   lock : true,
				   icoBasePath : icoBasePath,
				   icon : "error.gif"
			});
		},
		success: function(value)
		{
			var success = value.success;
			var info = value.info;
			if(success==1)
			{
				refreshAddress();
			}
			else
			{
				//alert(info);
				wep.dialog({
					   title : '消息',
					   content : info,
					   onyes : function(){
							this.close();
					   },
					   width : 200,
					   lock : true,
					   icoBasePath : icoBasePath,
					   icon : "error.gif"
				});
			}
		}
	});
	return true;
}
//获取地址
function refreshAddress()
{
	//alert(getAddressesAjaxUrl);
	$("#addressUl").html('');
	jQuery.ajax({
		type:'post',
		url: getAddressesAjaxUrl,
		dataType:"json",
		cache: false,
		async: true,
		error:function(value)
		{
			//alert("获取数据错误"+icoBasePath);
			var info = "获取数据错误";
			wep.dialog({
				   title : '消息',
				   content : info,
				   onyes : function(){
						this.close();
				   },
				   width : 200,
				   lock : true,
				   icoBasePath : icoBasePath,
				   icon : "error.gif"
			});
		},
		success: function(value) 
		{
			//alert(value.success);
			var success = value.success;
			var address = value.addressList;
			if(success==1)
			{
				//alert(address);
				var htmlContent = getAddressContent(address);
				$("#addressUl").html(htmlContent);
			}
			else
			{
				//alert(info);
				wep.dialog({
					   title : '消息',
					   content : info,
					   onyes : function(){
							this.close();
					   },
					   width : 200,
					   lock : true,
					   icoBasePath : icoBasePath,
					   icon : "error.gif"
				});
			}
		}
	});
}

function changeShippingMethod(obj)
{
	
	$("#shippingContent").html('');
	jQuery.ajax({
		type:'post',
		url: getActiveShippingListUrl, 
		dataType:"json",
		data:{'pay_mode':$(obj).val()},
		cache: false,
		async: true,
		success: function(value) 
		{
			if(value && value.success == 1){
				var info = value.info;
				var defaultCode = value.defaultVaule ; 
				currentDefaultShippingCode = defaultCode ; 
				var htmlContent = buildShippingContent(info , defaultCode);
				$("#shippingContent").html(htmlContent);
				refreshTotalAmount();
			}
		}
	});
}

function buildShippingContent(data , defaultCode)
{
	var htmlContent = '';
	if(data == undefined || data.length==0)
	{
		return '';
	}
	
	var xx = data.length;
	for(j=0;j<xx;j++)
	{
		htmlContent += buildOneShipingContent(data[j],j , defaultCode);
	}
	return htmlContent;
}

function buildOneShipingContent(shipping,j , defaultCode)
{
	var htmlContent = '';
	var disableCss = '' ;
	var disabled = '' ;
	if(0 == shipping.canUse)
    {
		disableCss = 'step_radio_disabled' ;
		disabled = 'disabled' ;
    }
	if(defaultCode == shipping.code)
	{
		htmlContent +='<div class="step_radio selected"><label for="shipping_method_'+shipping.id+'" style="background-image:url('+shipping.photo+')"><em>'+shipping.name+'</em></label><div class="note"><span>'+shipping.moreCosts+'</span></div><input type="radio" value="'+shipping.id+'" name="shipping_method" id="shipping_method_'+shipping.id+'" onchange="calculateShippingMethod()" code="'+shipping.code+'" checked /><i class="arrow"></i></div>';
	}
	else
	{
	    htmlContent +='<div class="step_radio '+disableCss+'"><label for="shipping_method_'+shipping.id+'" style="background-image:url('+shipping.photo+')"><em>'+shipping.name+'</em></label><div class="note"><span>'+shipping.moreCosts+'</span></div><input type="radio" value="'+shipping.id+'" name="shipping_method" id="shipping_method_'+shipping.id+'" onchange="calculateShippingMethod()" code="'+shipping.code+'" '+disabled+'/><i class="arrow"></i></div>';
	}
    
    return htmlContent;
}
/**
 * 根据ajax返回数据组装地址信息
 * @param jsonData
 * @returns {string}
 */
function getAddressContent(jsonData)
{
	var htmlContent = "";
	
	htmlContent += '<div class="clearfix step_radio_wrap">';
	//alert(jsonData.length);
	if(jsonData != undefined && jsonData.length == 1)
	{
		htmlContent += getOneAddressSelected(jsonData[0]);
	}
	if(jsonData != undefined && jsonData.length>1)
	{
		for(i=0;i<jsonData.length;i++)
		{
			htmlContent += getOneAddressContent(jsonData[i]);
		}
	}
	htmlContent += '</div>';
	htmlContent += '<div class="add_addr">';
	htmlContent += '	<a href="javascript:;" class="btn"><i class="add"></i><span>新增收货地址</span></a>';
	htmlContent += '</div>';
	return htmlContent;
}

function getOneAddressContent(oneData)
{
	var htmlContent = "";
	if(oneData.isDefault=="0")
	{
		htmlContent += '<div class="step_radio">';
		htmlContent += '<input type="radio" name="addressId" id="billing_address_id_'+oneData.addressId+'" provinceId="'+oneData.regionId+'" cityId="'+oneData.cityId+'" type="radio" value="'+oneData.addressId+'"/>';
		htmlContent += '<label for="billing_address_id_'+oneData.addressId+'">';
		htmlContent += '	<span class="city_name">'+oneData.areaInfo+'<em></em></span>';
		htmlContent += '	<span class="addr_tel">'+oneData.address+'<strong class="name">（<em>'+oneData.trueName+'</em>收）</strong> 联系电话：'+(oneData.mobPhone==null?oneData.telPhone:oneData.mobPhone)+'</span>';
		htmlContent += '</label>';
		htmlContent += '<div class="btns"><a href="javascript:;" data-addrid="'+oneData.addressId+'" class="btn edit"><span>修改地址</span></a><a href="javascript:;" onclick="saveAddressDefault('+oneData.addressId+')" class="btn set_def"><span>设为默认</span></a></div>';
		htmlContent += '<i class="arrow"></i>';
		htmlContent += '</div>';
	}
	else
	{
		htmlContent += '<div class="step_radio selected">';
		htmlContent += '<input type="radio" name="addressId" id="billing_address_id_'+oneData.addressId+'" provinceId="'+oneData.areaId+'" cityId="'+oneData.cityId+'" type="radio" value="'+oneData.addressId+'" checked/>';
		htmlContent += '<label for="addr_1">';
		htmlContent += '	<span class="city_name">'+oneData.areaInfo+'<em></em></span>';
		htmlContent += '	<span class="addr_tel">'+oneData.address+'<strong class="name">（<em>'+oneData.trueName+'</em>收）</strong>联系电话：'+(oneData.mobPhone==null?oneData.telPhone:oneData.mobPhone)+'</span>';
		htmlContent += '</label>';
		htmlContent += '<div class="btns"><a href="javascript:;" data-addrid="'+oneData.addressId+'" class="btn edit"><span>修改地址</span></a><span class="btn set_def span">已设为默认</span></div>';
		htmlContent += '<i class="arrow"></i>';
		htmlContent += '</div>';
	}
	return htmlContent;
}

function getOneAddressSelected(oneData)
{
	var htmlContent = "";
	if(oneData.isDefault=="0")
	{
		htmlContent += '<div class="step_radio selected">';
		htmlContent += '<input type="radio" name="addressId" id="billing_address_id_'+oneData.addressId+'" provinceId="'+oneData.areaId+'" cityId="'+oneData.cityId+'" type="radio" value="'+oneData.addressId+'" checked/>';
		htmlContent += '<label for="addr_1">';
		htmlContent += '	<span class="city_name">'+oneData.areaInfo+'<em></em></span>';
		htmlContent += '	<span class="addr_tel">'+oneData.address+'<strong class="name">（<em>'+oneData.trueName+'</em>收）</strong></span>';
		htmlContent += '</label>';
		htmlContent += '<div class="btns"><a href="javascript:;" data-addrid="'+oneData.addressId+'" class="btn edit"><span>修改地址</span></a></a><a href="javascript:;" onclick="saveAddressDefault('+oneData.addressId+')" class="btn set_def"><span>设为默认</span></a></div>';
		htmlContent += '<i class="arrow"></i>';
		htmlContent += '</div>';
	}
	else
	{
		htmlContent += '<div class="step_radio selected">';
		htmlContent += '<input type="radio" name="addressId" id="billing_address_id_'+oneData.addressId+'" provinceId="'+oneData.areaId+'" cityId="'+oneData.cityId+'" type="radio" value="'+oneData.addressId+'" checked/>';
		htmlContent += '<label for="addr_1">';
		htmlContent += '	<span class="city_name">'+oneData.areaInfo+'<em></em></span>';
		htmlContent += '	<span class="addr_tel">'+oneData.address+'<strong class="name">（<em>'+oneData.trueName+'</em>收）</strong></span>';
		htmlContent += '</label>';
		htmlContent += '<div class="btns"><a href="javascript:;" class="btn edit" data-addrid="'+oneData.addressId+'"><span>修改地址</span></a><span class="btn set_def span">已设为默认</span></div>';
		htmlContent += '<i class="arrow"></i>';
		htmlContent += '</div>';
	}
	return htmlContent;
}

function calculateShippingMethod()
{
	var shippingPrice = 0;
	var subtotal = $("#subtotal").html();
	subtotal = parseFloat(subtotal);
	var ob = $("#shippingContent") ,code = ob.find("input:checked").attr('code') ;
	if('y' == orderFreeShip){
		shippingPrice = 0;
	}
	else if(isYouZhi && !isPuTong){	//如果该订单优质包邮不计算运费
		shippingPrice = 0;
	}
	else if(!isYouZhi && isPuTong){	//该订单普通包邮需计算优质快递附加费
		var costs = getYouZhiShippingCosts(code);
		shippingPrice += parseFloat(costs);
	}
	else{
		if(subtotal < postageMin){
			shippingPrice += 10;
			var costs = getYouZhiShippingCosts(code);
			shippingPrice += parseFloat(costs);
		}
		if(subtotal >= postageMin && subtotal < postageMax){
			var costs = getYouZhiShippingCosts(code);
			shippingPrice += parseFloat(costs);
		}
		if(subtotal >= postageMax){
			shippingPrice += 0;
		}
	}
	//refreshTotalAmount();
}

//function needInvoiceChange()
//{
//	if($("#needInvoice").prop("checked")==true)
//	{
//		$(".taxN").html(toDecimal(parseFloat($("#subtotal").html())*taxrate,2));
//		$("#taxContent").show();
//		$("#taxDisplay").show();
//	}
//	else
//	{
//		$(".taxN").html(0);
//		$("#taxContent").hide();
//		$("#taxDisplay").hide();
//	}
//
//	refreshTotalAmount();
//}
//
//根据商品总金额算运费
function calculateShippingCosts(subtotal)
{
	var tmpShippingPrice = 0;
	subtotal = parseFloat(subtotal);
	var ob = $("#shippingContent") ,code = ob.find("input:checked").attr('code') ;
	if('y' == orderFreeShip){
		tmpShippingPrice = 0;
	}
	else if(isYouZhi && !isPuTong){	//如果该订单优质包邮不计算运费
		tmpShippingPrice = 0;
	}
	else if(!isYouZhi && isPuTong){	//该订单普通包邮需计算优质快递附加费
		var costs = getYouZhiShippingCosts(code);
		tmpShippingPrice += parseFloat(costs);
	}
	else{
		if(subtotal < postageMin){
			tmpShippingPrice += 10;
			var costs = getYouZhiShippingCosts(code);
			tmpShippingPrice += parseFloat(costs);
		}
		else if(subtotal >= postageMin && subtotal < postageMax){
			var costs = getYouZhiShippingCosts(code);
			tmpShippingPrice += parseFloat(costs);
		}
		else if(subtotal >= postageMax){
			tmpShippingPrice += 0;
		}
	}
	return tmpShippingPrice;
}

function getYouZhiShippingCosts(code){
	var totalShipping = 0;
	if('SF'== code || 'EMS' == code){
		totalShipping = parseFloat(moreShippingCosts).toFixed(2);
		$("#moreCosts").show() ;
	}
	else{
		totalShipping = 0;
		$("#moreCosts").hide() ;
	}
	return totalShipping;
}

//function refreshTotalAmount()
//{
//	var subtotal = $("#subtotal").html();
//	var giftcard = $("#gifcard_discount_span").html();
//	var cashcard = $("#cashcard_discount_span").html();//使用现金
//	var promotionDiscount = $("#pro_discount_span").html();
//	var gf_money = $("#cashcard_money").html() || 0;
//	var addamount = $("#use_save_act_span").html();
//
//	var totalAmount = (parseFloat(subtotal)*100 - parseFloat(giftcard)*100 - parseFloat(promotionDiscount)*100 + parseFloat(addamount)*100)/100;
//
//	//subtract cash card
//	//商品实付金额为负是置0
//	if(parseFloat(totalAmount) < 0.01){
//		totalAmount=0.00;
//	}
//
//	//重新计算运费 by paul yao
//	var tmpShippingPrice = calculateShippingCosts(subtotal);
//
//	if(totalAmount < parseFloat(gf_money))
//	{
//		cashcard = totalAmount;
//		$("#cashcard_discount_span").html(totalAmount);
//		$('#use_cashcard_money').html(totalAmount);
//	}
//	else
//	{
//		$('#use_cashcard_money').html(parseFloat(gf_money));
//	}
//
//	var totalAmount = parseFloat((totalAmount*100 - cashcard*100)/100).toFixed(2);
//	$("#cashcard_discount_span").html(parseFloat(cashcard));
//
//	//商品实付金额为负是置0
//	if(parseFloat(totalAmount) < 0.01){
//		totalAmount=0.00;
//	}
//	$("#ordered_amount").html(totalAmount);
//
//	//订单实付金额加上运费
//	totalAmount = parseFloat((totalAmount*100 + tmpShippingPrice*100)/100).toFixed(2);
//
//	$("#shippingPrice").html(tmpShippingPrice);
//	$("#order_totalAmount0").html(totalAmount);
//	$("#order_totalAmount1").html(totalAmount);
//	var receiveJifenAmount = (totalAmount*100 + cashcard*100 - NotReceiveJifenAmount*100 - tmpShippingPrice*100)/100;
//	//if(receiveJifenAmount > 0){
//	//	totalJf = parseInt(receiveJifenAmount / 5 * jifenMultiple);
//	//}
//	//$('#receiveJifen').html(totalJf);
//}

function showOtherInfoTip(info,type)
{
	if(type == "address")
	{
		location.hash = "#selectAddressH";
	}
	if(type == "pay")
	{
		location.hash = "#selectPaymentShippingH";
	}
	if(type == "shipping")
	{
		location.hash = "#selectShipping";
	}
	if(type == "invoice")
	{
		location.hash = "#invoice_service";
	}
	wep.dialog({
	   title : '消息提示',
	   content : info,
	   onyes : function(){
			this.hide();
	   },
	   width : 300,
	   lock : true,
	   icoBasePath : icoBasePath,
	   timeout : 3
	});
}

function focusInfoTip(info,id)
{
	wep.dialog({
	   title : '消息提示',
	   content : info,
	   onyes : function(){
			this.hide();
			$(id).focus();
	   },
	   width : 300,
	   lock : true,
	   icoBasePath : icoBasePath,
	   timeout : 3
	});
}

function saveOrder()
{
	//alert("saveOrder");
	//alert($('#remark').val());
	$("#saveOrder,a.checkout_now").hide();
	var address_id = $('input:radio[name="addressId"]:checked').val();
	if(typeof(address_id)=="undefined"){
		//alert("请选择收货地址！");
		$("#saveOrder,a.checkout_now").show();
		showInfoTip("请选择收货地址!","error");
		return;
	}
	var pay_mode = $('input:radio[name="paymentCode"]:checked').val();
	//var shipping_method = $('input:radio[name="shipping_method"]:checked').val();
	var need_invoice = $("#needInvoice").attr("checked") ? "1" : "0";
	var invoice_type = $('input:radio[name="invoice_type"]:checked').val();
	var invoice_title = $('#invoice_title').val();
	var invoice_content = $('input:radio[name="invoice_content"]:checked').val();
	var remark = $('#remark').val();
	var totalAmount = $('#order_totalAmount0').html();
	//alert(address_id+","+pay_mode+","+remark+","+totalAmount);
	var check = $('#need_giftcard').is(':checked');
	if(!check){
		$('#useVoucher').val(0);
		$('#voucherId').val('');
	}
	$("#error_info").html('');
	$(".have_error").removeClass("have_error");
	//if(stopSell == 'y')
	//{
	//	showOtherInfoTip("温馨提示：订单中存在下架商品，无法提交订单","product_list_tit_print");
	//	return;
	//}

	//if(address_id==undefined || address_id=="")
	//{
	//	showOtherInfoTip("温馨提示：请选择收货地址","address");
	//	return;
	//}
    //
	//if(pay_mode==undefined || pay_mode=="")
	//{
	//	showOtherInfoTip("温馨提示：请选择支付方式","pay");
	//	return;
	//}

	//if(shipping_method==undefined || shipping_method=="")
	//{
	//	showOtherInfoTip("温馨提示：请选择快递公司","shipping");
	//	return;
	//}

	//if(invoice_type == "corporate" && (invoice_title == undefined || invoice_title == ""))
	//{
	//	showOtherInfoTip("温馨提示：请填写发票抬头","invoice");
	//	return;
	//}
	ds.dialog.tips('<p style="padding-bottom:12px;text-align:center"><img src="'+icoBasePath+'loading.gif" alt="" /></p><p>正在提交订单，请稍后...</p>', 0, null, true);
	jQuery.ajax({
		type:'post',
		url: validateOrderUrl,
		dataType:"json",
		data:$("#onepageForm").serialize(),
		cache: false,
		async: true,
		success: function(value){
			//alert("validate order:"+value.success);
			if(value.success==0){
				ds.dialog.items.ds_dialog_tips.hide();
				var info = value.info;
				showErrorTip('温馨提示',info,'error');
			}else if(value.success==2){
				ds.dialog.items.ds_dialog_tips.hide();
				$("#error_info").fadeOut();

				var info = value.info;
				var hasGiftNoQty = value.hasGiftNoQty;
				var giftSkus = value.giftSkus;
				if(hasGiftNoQty){
					$("#noQtyGifts").val(giftSkus);
				}
				ds.dialog({
					title : '<span class="sadIcon">商品库存不足！</span>',
					content : info,
					onyes : function(){
						window.location.replace(getCartUrl);
						this.close();
					   },
					yesText : '返回购物车',
					buttons : [
							{
								text: hasGiftNoQty ? '忍了，继续提交订单':'联系客服',
								className: 'ds_dialog_yes',
								onclick: function(){
									if(hasGiftNoQty){
										this.close();
										ds.dialog.tips('<p style="padding-bottom:12px;text-align:center"><img src="'+icoBasePath+'loading.gif" alt="" /></p><p>正在提交订单，请稍后...</p>', 0, null, true);
										saveOrderAjax();
									}
									else{
										window.open(getAccountMessageUrl, '_blank');
									}
								}
							}
					]
				});
			}else{
				saveOrderAjax();
			}
		}
	});
	return;

}
//
function saveOrderAjax()
{
	//alert("begin ajax");
	jQuery.ajax({
		type:'post',
		url: saveOrderAjaxUrl,
		dataType:"json",
		data:$("#onepageForm").serialize(),
		cache: false,
		async: true,
		success: function(value)
		{
			ds.dialog.items.ds_dialog_tips.hide();
			function showOrder(data){
				alert("showOrder");
				var
				shell = $('#container').hide(),
				tmpl = $('#order_success_tmpl').val(),
				panel = $(document.createElement('div'));
				panel[0].className = shell[0].className + ' checkout_result';
				alert("show"+tmpl);

				panel.html(ds.tmpl(tmpl, data));
				shell.after(panel);
				panel.find('.info_box').attr('tabIndex', -1).focus();


				//pay
				//panel.delegate('form', 'submit', function(e){
				//	ds.dialog({
				//		padding: 20,
				//		showCloseButton: false,
				//		title: '支付中心支付',
				//		content: ds.tmpl($('#order_pay_dialog_tmpl').val(), data)
				//	});
				//	$(this).find('button').prop('disabled', true).addClass('disabled');
				//});
			}
			if(value.success==1)
			{
				//alert("success");
				//showOrder(value.info);
				var payNo = value.payNo;
				if(payNo){
					window.location = payinfoUrl+"?payNo="+payNo;
				}else{
					window.location = orderList+"?orderState=10";
				}
				//var data = value.info.order;
				//var orderId = data.orderId;
				//var orderNo = data.orderNo;
				//var totalAmount = data.totalAmount;
				//var typeText = data.typeText;
				//var shippingMethod = data.shippingMethod;
				//if(value.info.order.payType!='cod')
				//{
				//	$("#orderForm").submit();
				//}
				//sendToJuHe(orderNo,totalAmount);
				//sendToOrder(orderNo,typeText,shippingMethod);
			}
			else if(value.success==2)
			{
				showInfoTip("占用库存失败，请稍后再试","error");
			}
			else if(value.success==3)
			{
				showInfoTip(value.info,"error");
			}
			else{
				if(value.info=="notlogin")
				{
					window.location=loginUrl;
				}
				else
				{
					window.location=failureinfoUrl+"errorInfo/"+value.info;
				}
			}
		}
	});
}

function cancelOrder(orderId)
{
	$.ajax({
		type:'get',
		url: cancelOrderUrl,
		dataType:"json",
		data:{'order_id':orderId},
		cache: false,
		async: true,
		success: function(value){
			var success = value.success;
			var info = value.info;
			wep.dialog({
				   title : '消息',
				   content : info,
				   onyes : function(){
						this.close();
				   },
				   onhide : function(){
					   window.location.replace(orderUrl+'order_id/'+orderId);
				   },
				   width : 200,
				   lock : true
			});
		}
	});
}

function getOrderStatus(orderId)
{
	$.ajax({
		type:'get',
		url: getOrderStatusUrl,
		dataType:"json",
		data:{'order_id':orderId},
		cache: false,
		async: true,
		success: function(value){
			if(value){
				if(value.success == 0){
					ds.dialog({
						//width: 600,
						icon: 'error.png',
						title: '<strong>效验失败！</strong>',
						content: '<p style="color:red;font-size:14px">可能由于服务器或网络问题导致未能得到正确的效验结果，<br>如您确认已完成支付，请稍后查看订单支付状态。<br>如有任何疑问，请致电客服热线<em style="color:#F60;font-weight:bold;margin:0 .2em">400-607-8090</em>，我们将竭诚为您服务！</p>',
						onyes: true
					});
				}
				else if(value.success == 1){
					window.location.replace(orderUrl+'order_id/'+orderId);
				}
				else {
					showInfoTip('查询失败，请稍后查看订单支付状态');
				}
			}
		}
	});
}

function checkRemarkLength(obj,id)
{
	if(120-obj.value.length <=0)
	{
		jQuery("#"+id).html(0);
        obj.value=obj.value.substring(0,120);
        showPop('您输入的备注过长！',"error");
	}
	else
	{
		jQuery("#"+id).html(120-obj.value.length);
	}
}

//function showMoreAddress()
//{
//	if($("#showMore").html() == "显示全部")
//	{
//		var hideLi = $("#addressUl").find('li');
//		for(var i = 0; i < hideLi.length; i++)
//		{
//			$(hideLi[i]).show();
//		}
//		$("#showMore").html("收起");
//	}
//	else
//	{
//		var liArray = $("#addressUl").find('li');
//		for(var i = 0; i < liArray.length - 1; i++)
//		{
//			if(i > 4)
//			{
//				$(liArray[i]).attr('style','display:none');
//				$("#showMore").html("显示全部");
//			}
//		}
//	}
//}
//
//function changeInvoiceType(obj)
//{
//	$("#invoice_title").val("");
//	if(obj.checked && obj.value=='personal')
//	{
//		$("#invoice_title").hide();
//	}
//	else if(obj.checked && obj.value=='corporate')
//	{
//		$("#invoice_title").show();
//	}
//}
//
//
//
$(function(){
	$("#need_giftcard").change(function(e){
		if(this.checked)
		{
			loadGiftCard();
			$("#giftcard_twrap").show();
		}else
		{
			$("#giftcard_twrap").hide();
			$('#giftcard_table_body input[type="radio"]').each(function(){
				if(this.checked){
					$(this).prop("checked",false);
				}
			});
		}
	});
//	//click use cash card
//	$("#need_cashcard").change(function(){
//		if(this.checked)
//		{
//			loadCashCard();
//			$("#cashcard_twrap").show();
//		}else
//		{
//			$("#cashcard_twrap").hide();
//			$('#cashcard_table_body input[type="checkbox"]').each(function(){
//				if(this.checked){
//					$(this).prop("checked",false);
//				}
//			});
//			sumCashCard();
//			refreshAllGiftcard();
//		}
//	});
//
//	$("#need_promotioncode").change(function(e){
//		if(this.checked)
//		{
//			$("#promotioncode_twrap").show();
//		}else
//		{
//			$("#promotioncode_twrap").hide();
//		}
//	});
//	$("#useCashcard").change(function(e){
//		if(this.checked)
//		{
//			$('#cashcard_discount_span').html($('#use_cashcard_money').html());
//			$('#cashcard_discount_tr').show();
//		}else
//		{
//			$('#cashcard_table_body input[type="checkbox"]').each(function(){
//				if(this.checked){
//					$(this).prop("checked",false);
//				}
//			});
//			$('#cashcard_discount_span').html(0);
//			$('#cashcard_discount_tr').hide();
//			$('#use_cashcard').hide();
//			$('#need_cashcard').prop('checked',false);
//			$('#use_cashcard_tip').show();
//			$("#cashcard_money").html(0);
//		}
//		refreshTotalAmount();
//	});
//
//	$("#useGiftcard").change(function(e){
//		if(this.checked)
//		{
//			$('#gifcard_discount_span').html($('#use_giftcard_money').html());
//			$('#gifcard_discount_tr').show();
//
//			$('#need_promotioncode').prop('checked',false).attr('disabled',true);
//			$('#usePromotioncode').prop('checked',false).attr('disabled',true).change();
//			$('#promotioncode_twrap').attr('style','display:none');
//
//		}else
//		{
//			$('#giftcard_table_body input[type="checkbox"]').each(function(){
//				if(this.checked){
//					$(this).prop("checked",false);
//				}
//			});
//			$('#gifcard_discount_span').html(0);
//			$('#gifcard_discount_tr').hide();
//			$('#use_giftcard').hide();
//			$('#need_giftcard').prop('checked',false);
//			$('#use_giftcard_tip').show();
//
//			$('#need_promotioncode').attr('disabled',false);
//			$('#usePromotioncode').attr('disabled',false);
//		}
//		refreshTotalAmount();
//	});
//
//	$("#usePromotioncode").change(function(e){
//		if(this.checked)
//		{
//			$('#pro_discount_span').html($('#promotioncode_money').html());
//			$('#pro_discount_tr').show();
//		}
//		else
//		{
//			$('#pro_discount_span').html(0);
//			$('#pro_discount_tr').hide();
//		}
//		refreshTotalAmount();
//		refreshAllGiftcard();
//	});
});
//
//$(function(){
//	var obj2 = $("#pay_mode2").bind('change',function(e){
//		var we = $("#need_we_exchange");
//		if(we.attr("checked"))
//		{
//			we.click();
//		}
//		we.attr("disabled",true);
//		$('#we_exchange_tip').show();
//		$('#we_exchange_use').hide();
//		$('#we_discont_span').html(0);
//		$('#we_discont_tr').hide();
//		refreshTotalAmount();
//	});
//	var obj1 = $("#pay_mode1").bind('change',function(e){
//		refreshTotalAmount();
//	});
//	if(obj1.prop("checked"))
//	{
//		obj1.change();
//	}
//	if(obj2.prop("checked"))
//	{
//		obj2.change();
//	}
//});
//
function loadGiftCard()
{
	var obj = $("#giftcard_table");
	var obj1 = $("#giftcard_table_body").html('');
	$('#giftcard_used').html('');
	var subtotal = $("#subtotal").html();
	jQuery.ajax({
		type:'post',
		url: getGiftCardUrl,
		dataType:"json",
		data:{"total_amount":subtotal},
		cache: false,
		async: true,
		success: function(value)
		{
			if(value)
			{
				value = value.list;
				if(value && value.length >0)
				{
					obj.data("dataList",value);
					var data;
					var clas = "even";
					var htmlContent = '';
					for(var i=0;i<value.length;i++)
					{

						data = value[i];
						htmlContent += '<tr class='+clas+'><td><input type="radio" name="voucherId" value="'+data.voucherId+'"';
						htmlContent += '</td><td class="price">'+data.voucherPrice+'元</td><td>'+data.startDate+'--'+data.endDate+'</td><td>'+data.voucherDesc+'</td></tr>';
					}
					obj1.html(htmlContent);

				}else
				{
					obj1.html('<tr><td colspan="6" align="center">>_<||| 暂无可用的优惠券...</td></tr>');
				}
			}else
			{
				showInfoTip(value.info);
			}
		}
	});
}
//
//function loadCashCard()
//{
//	var obj = $("#cashcard_table");
//	var obj1 = $("#cashcard_table_body").html('');
//	$('#cashcard_used').html('');
//	var subtotal = $("#subtotal").html();
//	jQuery.ajax({
//		type:'post',
//		url: getCashCardUrl,
//		dataType:"json",
//		data:{"total_amount":cartSubtotal},
//		cache: false,
//		async: true,
//		success: function(value)
//		{
//			if(value.success)
//			{
//				value = value.info;
//				if(value && value.length >0)
//				{
//					obj.data("dataList",value);
//					var data;
//					var clas = "even";
//					var htmlContent = '';
//					var isOld = false;
//					for(var i=0;i<value.length;i++)
//					{
//						data = value[i];
//						if(data.type == 2 || data.type == 3)
//						{
//							continue;
//						}
//						if(i % 2 != 0)
//						{
//							clas = "even";
//						}else
//						{
//							clas = "";
//						}
//						htmlContent += '<tr class='+clas+'><td><input type="checkbox" name="cashcardno[]" value="'+data.no+'"';
//						if(data.isOlde == 1)
//						{
//							htmlContent += ' checked ';
//							isOld = true;
//						}
//						if(data.type == 1)
//						{
//							htmlContent += ' category="1" price="'+data.discount+'" onchange="useGiftcardtest(this)"></td><td>现金卡';
//						}
//						htmlContent += '</td><td>'+data.hideno+'</td><td class="price">'+data.discount+'元</td><td>'+data.extime+'</td><td>'+data.desp+'</td></tr>';
//					}
//					obj1.html(htmlContent);
//					obj.data("isload","y");
//					refreshAllGiftcard();
//					if(isOld)
//					{
//						sumCashCard();
//					}
//
//				}else
//				{
//					obj1.html('<tr><td colspan="6" align="center">>_<||| 暂无可用的现金卡...</td></tr>');
//				}
//			}else
//			{
//				showInfoTip(value.info);
//			}
//		}
//	});
//}
//
//function useGiftcardtest(obj)
//{
//	var objt = $(obj);
//	var objc = objt.parent().parent();
//	if(objt.attr("checked"))
//	{
//		objc.addClass("selected");
//	}else
//	{
//		objc.removeClass("selected");
//	}
//	if(objt.attr('category') == "1")
//	{
//		sumCashCard();
//	}
//	else
//	{
//		sumGiftCard();
//	}
//	var current_ordered_amount = $("#ordered_amount").html(),limitCanUse = parseFloat(current_ordered_amount);
//
//	var cashcardCheckboxs = $('#cashcard_table_body input[category="1"]').prop('disabled', false),
//		cashcardChecked = cashcardCheckboxs.filter(':checked');
//	var bulecardCheckboxs = $('#giftcard_table_body input[category="2"]').prop('disabled', false),
//		bulecardChecked = bulecardCheckboxs.filter(':checked');
//	var redcardCheckboxs = $('#giftcard_table_body input[category="3"]').prop('disabled', false),
//		redcardChecked = redcardCheckboxs.filter(':checked');
//
//	 if(limitCanUse == 0)
//	 {
//		 cashcardCheckboxs.filter(':not(:checked)').prop('disabled', true);
//		 bulecardCheckboxs.filter(':not(:checked)').prop('disabled', true);
//		 redcardCheckboxs.filter(':not(:checked)').prop('disabled', true);
//	 }
//	 else
//	 {
//		 cashcardCheckboxs.filter(':not(:checked)').prop('disabled', false);
//		 bulecardCheckboxs.filter(':not(:checked)').prop('disabled', false);
//		 redcardCheckboxs.filter(':not(:checked)').prop('disabled', false);
//	 }
//	 if(cashcardChecked.length >= greencardNum)
//	 {
//		 cashcardCheckboxs.filter(':not(:checked)').prop('disabled', true);
//	 }
//	 if(bulecardChecked.length >= bluecardNum)
//	 {
//		 bulecardCheckboxs.filter(':not(:checked)').prop('disabled', true);
//	 }
//	 if(redcardChecked.length >= redcardNum)
//	 {
//		 redcardCheckboxs.filter(':not(:checked)').prop('disabled', true);
//	 }
//}
//
//function refreshAllGiftcard()
//{
//		sumCashCard();
//		sumGiftCard();
//	var current_ordered_amount = $("#ordered_amount").html(),limitCanUse = parseFloat(current_ordered_amount);
//
//	var cashcardCheckboxs = $('#cashcard_table_body input[category="1"]').prop('disabled', false),
//		cashcardChecked = cashcardCheckboxs.filter(':checked');
//	var bulecardCheckboxs = $('#giftcard_table_body input[category="2"]').prop('disabled', false),
//		bulecardChecked = bulecardCheckboxs.filter(':checked');
//	var redcardCheckboxs = $('#giftcard_table_body input[category="3"]').prop('disabled', false),
//		redcardChecked = redcardCheckboxs.filter(':checked');
//
//	 if(limitCanUse == 0)
//	 {
//		 cashcardCheckboxs.filter(':not(:checked)').prop('disabled', true);
//		 bulecardCheckboxs.filter(':not(:checked)').prop('disabled', true);
//		 redcardCheckboxs.filter(':not(:checked)').prop('disabled', true);
//	 }
//	 else
//	 {
//		 cashcardCheckboxs.filter(':not(:checked)').prop('disabled', false);
//		 bulecardCheckboxs.filter(':not(:checked)').prop('disabled', false);
//		 redcardCheckboxs.filter(':not(:checked)').prop('disabled', false);
//	 }
//	 if(cashcardChecked.length >= greencardNum)
//	 {
//		 cashcardCheckboxs.filter(':not(:checked)').prop('disabled', true);
//	 }
//	 if(bulecardChecked.length >= bluecardNum)
//	 {
//		 bulecardCheckboxs.filter(':not(:checked)').prop('disabled', true);
//	 }
//	 if(redcardChecked.length >= redcardNum)
//	 {
//		 redcardCheckboxs.filter(':not(:checked)').prop('disabled', true);
//	 }
//}
//
function sumGiftCard()
{
	var giftcardObj = $("#giftcard_used").html('');
	var obj = {};
	var dataList = $("#giftcard_table").data("dataList");
	$("#giftcard_table_body").find("[type='checkbox']").each(function(i){
		if(this.checked)
		{
			var obj1 = dataList[i];
			var type = obj1.type;
			if(!obj[type])
			{
				obj[type] = {};
			}
			obj[type].count = (obj[type].count || 0) +1;
			if(!obj[type].sum)
			{
				obj[type].sum = 0;
			}
			obj[type].sum += obj1.discount;
			if(!obj[type].txt)
			{
				obj[type].txt = "";
			}else
			{
				obj[type].txt += "+";
			}
			obj[type].txt += obj1.discount;
		}
	});

	var allsum = 0;
	for(key in obj)
	{
		var htmlContent = '<li><strong>';
		if(key == 1)
		{
			htmlContent += '绿卡';
		}
		if(key == 2)
		{
			htmlContent += '优惠券';
		}
		if(key == 3)
		{
			htmlContent += '优惠券';
		}
		allsum += obj[key].sum;
		var tmp = parseFloat(obj[key].sum).toFixed(2);
		htmlContent += '：</strong>已使用<em id="gf_count">'+obj[key].count+'</em>张 共 <em id="gf_money">'+tmp+'</em> ('+obj[key].txt+'='+tmp+'元)</li>'
		giftcardObj.append(htmlContent);
	}
	if(allsum == 0)
	{
		$("#gifcard_discount_tr").hide();
	}else
	{
		$("#gifcard_discount_tr").show();
	}
	allsum = parseFloat(allsum).toFixed(2);
	$("#gifcard_discount_span").html(allsum);
	//refreshTotalAmount();
}
//
//function sumCashCard()
//{
//	var cashcardObj = $("#cashcard_used").html('');
//	var obj = {};
//	var dataList = $("#cashcard_table").data("dataList");
//	$("#cashcard_table_body").find("input:[type=checkbox]").each(function(i){
//		if(this.checked)
//		{
//			var obj1 = dataList[i];
//			var type = obj1.type;
//			if(!obj[type])
//			{
//				obj[type] = {};
//			}
//			obj[type].count = (obj[type].count || 0) +1;
//			if(!obj[type].sum)
//			{
//				obj[type].sum = 0;
//			}
//			obj[type].sum += obj1.discount;
//			if(!obj[type].txt)
//			{
//				obj[type].txt = "";
//			}else
//			{
//				obj[type].txt += "+";
//			}
//			obj[type].txt += obj1.discount;
//		}
//	});
//
//	var allsum = 0;
//	for(key in obj)
//	{
//		var htmlContent = '<li><strong>';
//		if(key == 1)
//		{
//			htmlContent += '现金卡';
//		}
//		if(key == 2)
//		{
//			htmlContent += '优惠券';
//		}
//		if(key == 3)
//		{
//			htmlContent += '优惠券';
//		}
//		allsum += obj[key].sum;
//		var tmp = parseFloat(obj[key].sum).toFixed(2);
//		htmlContent += '：</strong>已使用<em id="cash_count">'+obj[key].count+'</em>张 共 <em id="cashcard_money">'+tmp+'</em> ('+obj[key].txt+'='+tmp+'元)</li>'
//		cashcardObj.append(htmlContent);
//	}
//	if(allsum == 0)
//	{
//		$("#cashcard_discount_tr").hide();
//	}else
//	{
//		$("#cashcard_discount_tr").show();
//	}
//	allsum = parseFloat(allsum).toFixed(2);
//	$("#cashcard_discount_span").html(allsum);
//	refreshTotalAmount();
//}
//
//var actData = "";
//
//$(function(){
//	$("#use_save_act").change(function(e){
//		if(this.checked)
//		{
//			$("#use_save_act_div").show();
//			if(actData==""){
//				loadActivityProduct();
//			}
//		}else
//		{
//			$("#use_save_act_div").hide();
//		}
//		showact();
//		refreshTotalAmount();
//	});
//
//	$('#use_save_act_div').delegate('select', 'change', function(e){
//		e.preventDefault();
//		var info = $(this).parent().parent().parent().find(".pro_info");
//		var itemid = $(this).val();
//		var infohtml = bulidProductHtml(itemid);
//		if( infohtml.indexOf("group=") ==0 ){
//			var groupid = infohtml.substr(6);
//			showSelectProduct(itemid,groupid,info);
//		}else{
//			info.html(infohtml);
//			info.show();
//
//			showact();
//			refreshTotalAmount();
//		}
//	})
//	.change(function(e){
//		e.stopPropagation();
//	});
//
//});
//
//function showact(){
//	var addamount = 0;
//	var useact = $("#use_save_act");
//	if(useact.attr("checked")){
//		var iptaddamount = $("input[name='actitem[addamount][]']");
//
//		for(var i=0;i<iptaddamount.length;i++){
//			var ipt = iptaddamount[i];
//			addamount = addamount + parseFloat(ipt.value);
//		}
//		$("#use_save_act_span").html(parseFloat(addamount).toFixed(2));
//		$("#use_save_act_tr").show();
//	}else{
//		$("#use_save_act_span").html(0);
//		$("#use_save_act_tr").hide();
//	}
//}
//
//function loadActivityProduct()
//{
//	$("#use_save_act_div").html(loadingStr);
//	var subtotal = $("#subtotal").html();
//	jQuery.ajax({
//		type:'post',
//		url: getActivityProductUrl+"?amount="+subtotal,
//		dataType:"json",
//		cache: false,
//		async: true,
//		success: function(value)
//		{
//			if(value.success)
//			{
//				value = value.info;
//				actData = value;
//				buildActivityProductHtml(value);
//			}else
//			{
//				showInfoTip(value.info);
//			}
//		}
//	});
//}
//
//function buildActivityProductHtml(jsonData){
//	var html = "";
//	for(var i=0;i<jsonData.length;i++){
//		var activitybuy = jsonData[i]["head"];
//		var activitybuyitem = jsonData[i]["detail"];
//		var addAmount = activitybuy["add_amount"];	//加xx金额可换购
//
//		html += '<div class="save_item">';
//		html += '<span class="pre_info">加'+addAmount+'</span>';
//		html += '<span class="info">';
//		html += '	<span class="label">可换购：</span>';
//		html += '	<span class="choose">';
//		html += '		<select name="choose" onchange="chooseProduct();">';
//		html += '			<option value="0">-- 请选择换购商品 --</option>';
//		for(var j=0; j<activitybuyitem.length; j++ ) {
//			var item = activitybuyitem[j];
//			html += '				<option value="'+item["id"]+'" >'+item["name"]+'</option>';
//		}
//		html += '	</select>';
//		html += '</span>';
//		html += '</span>';
//		html += '<div class="pro_info" style="display:none">';
//		html += '</div>';
//		html += '</div>';
//	}
//	$("#use_save_act_div").html(html);
//}
//
//function chooseProduct()
//{
//	$count = 0;
//	var selects = $('select[name="choose"]');
//	for(var i= 0; i < selects.length; i++)
//	{
//		if($(selects[i]).val() != 0)
//		{
//			$count++;
//		}
//	}
//	if($count >= 2)
//	{
//		for(var i= 0; i < selects.length; i++)
//		{
//			if($(selects[i]).val() == 0)
//			{
//				$(selects[i]).attr('disabled',true);
//			}
//		}
//	}
//	else
//	{
//		for(var i= 0; i < selects.length; i++)
//		{
//			if($(selects[i]).val() == 0)
//			{
//				$(selects[i]).attr('disabled',false);
//			}
//		}
//	}
//}
//
//function bulidProductHtml(itemid){
//	var html = "";
//	for(var i=0;i<actData.length;i++){
//		var activitybuy = actData[i]["head"];
//		var activitybuyitem = actData[i]["detail"];
//		for(var j=0; j<activitybuyitem.length; j++ ) {
//			var item = activitybuyitem[j];
//			if(item["id"] == itemid){
//				if(item["type"]=="group"){
//					return "group="+item["product_id"];
//				}else{
//					html += item["img"];
//					html += '<a href="'+item["productUrl"]+'" target="_blank" class="tit">'+item["name"]+'</a>';
//					html += '<span class="old_price">原价：<em>&yen;'+item["price"]+'</em></span>';
//					html += '<input type="hidden" value="'+item["id"]+'" name="actitem[id][]"/>';
//					html += '<input type="hidden" value="'+item["ref_id"]+'" name="actitem[refid][]"/>';
//					html += '<input type="hidden" value="'+item["product_id"]+'" name="actitem[productid][]"/>';
//					html += '<input type="hidden" value="'+activitybuy["add_amount"]+'" name="actitem[addamount][]"/>';
//				}
//
//				break;
//			}
//		}
//	}
//	return html;
//}
//
//function showSelectProduct(itemid,groupid,showObj){
//	jQuery.ajax({
//		type:'post',
//		url: getActivityProductGroupUrl,
//		dataType:"json",
//		data:{'parentid':groupid},
//		cache: false,
//		async: false,
//		beforeSend:function(){
//		},
//		complete:function(){
//		},
//		error:function(value){
//		},
//		success: function(value){
//			if(value.success==1){
//
//				var info = value.info;
//				wep.dialog({
//					title : '选择活动商品',
//					content : info,
//					onyes : function(){
//						var pId = selectProduct();
//						if(pId){
//							loadActivityProductByPID(itemid,pId,showObj);
//							this.close();
//						}else{
//							resetSelect(showObj);
//						}
//					},
//					yesText : '确认',
//					onno : function(){resetSelect(showObj);},
//					noText : '取消',
//					icoBasePath : icoBasePath
////					icon : "question.gif"
//				});
//
//				$("input[name='check_act_radio']").change(function(e){
//					$(this).parent().parent().parent().find(".checked").removeClass("checked");
//					$(this).parent().parent().addClass("checked");
//				});
//			}else{
//
//			}
//		}
//	});
//}
//
//function loadActivityProductByPID(itemid,productid,showObj){
//	jQuery.ajax({
//		type:'post',
//		url: getActivityProductByPIDUrl,
//		dataType:"json",
//		data:{'productid':productid},
//		cache: false,
//		async: true,
//		success: function(value)
//		{
//			if(value.success)
//			{
//				value = value.info;
//				var infohtml = bulidProductHtml2(itemid,value);
//				showObj.html(infohtml);
//				showObj.show();
//
//				showact();
//				refreshTotalAmount();
//
//			}else
//			{
//				showInfoTip(value.info);
//			}
//		}
//	});
//}
//
//function resetSelect(showObj){
//	var lastval = showObj.find("input[name='actitem[id][]']");
//	if(lastval.length>0){
//		lastval = lastval.val();
//	}else{
//		lastval = "0";
//	}
//	showObj.parent().find("select").val(lastval);
//}
//
//function bulidProductHtml2(itemid,product){
//	var html = "";
//	var productid = product.productid;
//	var productname = product.name;
//	var producturl = product.productUrl;
//	var img = product.img;
//	var price = product.price;
//	for(var i=0;i<actData.length;i++){
//		var activitybuy = actData[i]["head"];
//		var activitybuyitem = actData[i]["detail"];
//		for(var j=0; j<activitybuyitem.length; j++ ) {
//			var item = activitybuyitem[j];
//			if(item["id"] == itemid){
//
//				html += img;
//				html += '<a href="'+producturl+'" target="_blank" class="tit">'+productname+'</a>';
//				html += '<span class="old_price">原价：<em>&yen;'+price+'</em></span>';
//				html += '<input type="hidden" value="'+item["id"]+'" name="actitem[id][]"/>';
//				html += '<input type="hidden" value="'+item["ref_id"]+'" name="actitem[refid][]"/>';
//				html += '<input type="hidden" value="'+productid+'" name="actitem[productid][]"/>';
//				html += '<input type="hidden" value="'+activitybuy["add_amount"]+'" name="actitem[addamount][]"/>';
//
//				break;
//			}
//		}
//	}
//	return html;
//}
//
////check_act_radio
//function selectProduct(){
//	var productIDObj = $("input[name='check_act_radio']:checked");
//	if(productIDObj.length > 0){
//		return productIDObj.val();
//	}else{
//		showInfoTip("请选择商品！","error");
//		return false;
//	}
//}
//
function showErrorTip(tit,info,type)
{
	var icon = "error.gif";

	if(type != null)
	{
		if(type == "success")
		{
			icon = "success.gif";
		}else if(type == "info")
		{
			icon = "info.gif";
		}
	}
	wep.dialog({
	   title : tit,
	   content : info,
	   onyes : function(){
			this.hide();
	   },
	   width : 400,
	   lock : true,
	   icoBasePath : icoBasePath,
	   icon : icon,
	   timeout : 3
	});
}

function invoiceModifiy(){
	$("#modify_invoice").hide();
	$(".invoice_choose_inner").show();
	if(invoiceType == '' || invoiceType == 1){
		$("#defaultInvoiceView").hide();
		$("#default_invoice").show()
	}
	if(invoiceType == 2){
		$("#vatInvoiceView").hide();
		$("#vat_invoice").show();
	}
}
/**
 * 发票抬头是公司/个人切换
 */
function changeInvoiceTitle(){
	var selected = $('#invoice_title').val();
	//alert(selected);
	if(selected==1){
		$('#invoice_title_txt').hide();
		$('#invoice_tips').hide();
	}else{
		$("#invoice_tips").html("*");
		$('#invoice_title_txt').show();
		$('#invoice_tips').show();
	}

}
function changeInvoiceType(){
	var type = $('input[name=invoice_type]:checked').val();
	if(type == 1){
		$("#vat_invoice").hide();
		$("#default_invoice").show();
	}
	else{
		$("#default_invoice").hide();
		$("#vat_invoice").show();
	}
}

function cancelInvoice(){
	$('.invoice_choose_inner').hide();
	$('#default_invoice').hide();
	$('#vat_invoice').hide();
	$('#modify_invoice').html('<em>不需要发票</em><span>【<a href="javascript:;" onclick="invoiceModifiy();">修改</a>】</span>').show();
	$('#v_need_invoice').val('0');
	$('#v_invoice_type').val('');
	$('#v_invoice_title_type').val('');
	$('#v_invoice_title').val('');
	$('#v_company_name').val('');
	$('#v_identify_number').val('');
	$('#v_company_address').val('');
	$('#v_company_telephone').val('');
	$('#v_bank_name').val('');
	$('#v_bank_account').val('');
	$('#invoice_normal').prop("checked",true);
	$('#invoice_added').prop("checked",false);
	jQuery.ajax({
		type:'post',
		url: cancelInvoiceUrl,
		dataType:"json",
		cache: false,
		async: true,
		success: function(value) {
			invoiceType = '';
		}
	});
}

function saveDefaultInvoice(){
	//alert("保存发票");
	var invoice_type = $('input[name=invoice_type]:checked').val();
	var title_type = $('#invoice_title').val();
	var title = $('#invoice_title_txt').val();
	//alert(invoice_type+",title:"+title_type+",content:"+title+","+saveDefaultInvoiceUrl);
	if(title_type==2 && isEmpty(title)){
		//alert("sss");
		//focusInfoTip("温馨提示：请填写发票抬头","#invoice_title_txt");
		//showInfoTip("温馨提示：请填写发票抬头","error");
		$("#invoice_title_txt").focus();
		$("#invoice_tips").html("请填写发票抬头 *");
		return;
	}
	//发票明细
	var content = $("#invoice_content").find("option:selected").text();
	var title_name = title_type==1?"个人":title;
	//增值税发票暂时不支持
	//$('#v_need_invoice').val('1');
	//$('#v_invoice_type').val(invoice_type);
	//$('#v_invoice_title_type').val(title_type);
	//$('#v_invoice_title').val(title);
	//$('#v_company_name').val('');
	//$('#v_identify_number').val('');
	//$('#v_company_address').val('');
	//$('#v_company_telephone').val('');
	//$('#v_bank_name').val('');
	//$('#v_bank_account').val('');
	jQuery.ajax({
		type:'post',
		url: saveDefaultInvoiceUrl,
		dataType:"json",
		data:{"invState":invoice_type,"invTitle":title_name,"invContent":content},
		cache: false,
		async: true,
		success: function(value)
		{
			//alert(value);
			if(value){
				var success = value.success;
				var info = value.invoice;
				//alert(success+","+info)
				if(success == 1){
					invoiceType = 1;
					$('.invoice_choose_inner').hide();
					$("#default_invoice").hide();
					//if(info.invState == 1){
					//	$('#invoice_normal').prop("checked",true);
					//}
					//if(info.invState == 2){
					//	$('#invoice_added').prop("checked",true);
					//}
					var titleType = '普通发票';
					if(info.invState == 1){
						titleType = '普通发票';
					}
					if(info.invState == 2){
						titleType = '增值税专用发票';
					}
					$("#invoice_title").val(titleType);
					$("#viewTitleType").html(titleType);
					$("#invoice_title_txt").val(info.invTitle);
					$("#viewTitle").html(info.invTitle);
					$("#modify_invoice").html('<em>需要发票</em><span>【<a href="javascript:;" onclick="invoiceModifiy();">修改</a>】</span>').show();
					$("#defaultInvoiceView").show();
					$("#invoice_title").val(info.invContent);
				}
				else{
					showInfoTip(info,"info");
				}
			}
		}
	});
}
//
//function saveVatInvoice(){
//	var invoice_type = $('input[name=invoice_type]:checked').val();
//	var company_name = $('#company_name').val();
//	var identify_number = $('#identify_number').val();
//	var address = $('#address').val();
//	var telephone = $('#telephone').val();
//	var bank_name = $('#bank_name').val();
//	var bank_account = $('#bank_account').val();
//	if(!company_name){
//		focusInfoTip("温馨提示：请填写公司名称","#company_name");
//		return;
//	}
//	if(!identify_number){
//		focusInfoTip("温馨提示：请填写纳税人识别号","#identify_number");
//		return;
//	}
//	if(!address){
//		focusInfoTip("温馨提示：请填写公司地址","#address");
//		return;
//	}
//	if(!telephone){
//		focusInfoTip("温馨提示：请填写公司电话","#telephone");
//		return;
//	}
//	if(!bank_name){
//		focusInfoTip("温馨提示：请填写开户行名称","#bank_name");
//		return;
//	}
//	if(!bank_account){
//		focusInfoTip("温馨提示：请填写开户行账号","#bank_account");
//		return;
//	}
//	$('#v_need_invoice').val('1');
//	$('#v_invoice_type').val(invoice_type);
//	$('#v_invoice_title_type').val('');
//	$('#v_invoice_title').val('');
//	$('#v_company_name').val(company_name);
//	$('#v_identify_number').val(identify_number);
//	$('#v_company_address').val(address);
//	$('#v_company_telephone').val(telephone);
//	$('#v_bank_name').val(bank_name);
//	$('#v_bank_account').val(bank_account);
//	jQuery.ajax({
//		type:'post',
//		url: saveVatInvoiceUrl,
//		dataType:"json",
//		data:{"invoice_type":invoice_type,"company_name":company_name,"identify_number":identify_number,"address":address,"telephone":telephone,"bank_name":bank_name,"bank_account":bank_account},
//		cache: false,
//		async: true,
//		success: function(value){
//			if(value){
//				var success = value.success;
//				var info = value.info;
//				if(success == 1){
//					invoiceType = 2;
//					$('.invoice_choose_inner').hide();
//					$("#vat_invoice").hide();
//					var titleType = '普通发票';
//					if(info.invoice_type == 1){
//						titleType = '普通发票';
//					}
//					if(info.invoice_type == 2){
//						titleType = '增值税专用发票';
//					}
//					$("#viewVatTitleType").html(titleType);
//					$('#companyNameView').html(info.company_name);
//					$('#identifyNumberView').html(info.identify_number);
//					$('#addressView').html(info.address);
//					$('#telephoneView').html(info.telephone);
//					$('#bankNameView').html(info.bank_name);
//					$('#bankAccountView').html(info.bank_account);
//					$("#modify_invoice").html('<em>需要发票</em><span>【<a href="javascript:;" onclick="invoiceModifiy();">修改</a>】</span>').show();
//					$("#vatInvoiceView").show();
//				}
//				else{
//					showInfoTip(info,"info");
//				}
//			}
//		}
//	});
//}
//
//function checkPromotioncode(){
//	var promotionCode = $('#promotionCode').val();
//	if(!promotionCode){
//		focusInfoTip("温馨提示：请填写正确的优惠代码","#promotionCode");
//		return;
//	}
//	var current_ordered_amount = $("#ordered_amount").html();
//    var limitCanUse = parseFloat(current_ordered_amount).toFixed(2);
//	if(limitCanUse<=0){
//		focusInfoTip("温馨提示：订单金额已经为0","#promotionCode");
//		return;
//	}
//	jQuery.ajax({
//		type:'post',
//		url: checkPromotionCodeUrl,
//		dataType:"json",
//		data:{"promotionCode":promotionCode},
//		cache: false,
//		async: true,
//		success: function(value){
//			if(value && value.success == 1){
//				var info = value.info;
//				$('#promotioncode_tip').hide();
//				$("#promotioncode_money").html(info.discount);
//				$('#usePromotioncode').prop('checked',true);
//				$("#use_promotioncode").show();
//				$("#promotioncode_twrap").hide();
//				$("#pro_discount_span").html(info.discount);
//				$("#pro_discount_tr").show();
//
//				refreshTotalAmount();
//				refreshAllGiftcard();
//			}
//			else{
//				showInfoTip(value.info,"info");
//			}
//		}
//	});
//}



